<?php

namespace mbilling\BillingBundle\Model;

use Doctrine\ORM\EntityManager;
use mbilling\BillingBundle\Entity\ordersVps;


Class OrdersVpsModel
{
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function findAll()
    {
        $orders = $this->em->getRepository('BillingBundle:ordersVps')->findAll();
        return $orders;
    }
    
    public function findByUserId($user_id)
    {
        $query = $this->em->createQuery('SELECT oV FROM BillingBundle:ordersVps oV WHERE oV.order_id = ANY
                                    (SELECT o FROM BillingBundle:orders o WHERE o.user_id = '.$user_id.')');
        $orders = $query->getResult();
        return $orders;
    }

    public function findByOrderId($order_id)
    {
        $order = $this->em->getRepository('BillingBundle:ordersVps')->findOneBy(array('order_id' => $order_id));
        return $order;
    }
    
    public function findByPK($order_id)
    {
        $order = $this->em->find('BillingBundle:ordersVps', $order_id);
        return $order;
    }
    
    public function create($oEntity, $os, $tarif, $order)
    {
        $oEntity->setCpu($tarif->getCpu());
        $oEntity->setRam($tarif->getRam());
        $oEntity->setHdd($tarif->getHdd());
        $oEntity->setDedIpCount($tarif->getDedIpCount());
        $oEntity->setDnsAccess($tarif->getDnsAccess());
        $oEntity->setIsChanged('0');
        $oEntity->setOs($os->getId());
        $oEntity->setOrderId($order->getId());
        $oEntity->setVpsTarif($tarif->getId());
        $oEntity->setName("VPS".$order->getId());
        $this->em->persist($oEntity);
        $this->em->flush();
    }

    public function update($oEntity, $user, $os, $tarif, $order)
    {
        if (!$user->isAdmin())
        {
            $oEntity->setCpu($tarif->getCpu());
            $oEntity->setRam($tarif->getRam());
            $oEntity->setHdd($tarif->getHdd());
            $oEntity->setDedIpCount($tarif->getDedIpCount());
            $oEntity->setDnsAccess($tarif->getDnsAccess());
            $oEntity->setIsChanged('0');
            $oEntity->setName("VPS".$order->getId());
        }
        $oEntity->setOs($os->getId());
        $oEntity->setOrderId($order->getId());
        $oEntity->setVpsTarif($tarif->getId());
        $this->em->persist($oEntity);
        $this->em->flush();
    }
    
    public function removeByPK($order_id)
    {
        $order = $this->em->find('BillingBundle:ordersVps', $order_id);
        $this->em->remove($order);
        $this->em->flush();
    }

    public function removeByOrderId($order_id)
    {
        $order = $this->em->getRepository('BillingBundle:ordersVps')->findOneBy(array('order_id' => $order_id));
        $this->em->remove($order);
        $this->em->flush();
    }
}
?>
